package com.mystnihon.freeremote.ui.fragment;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.mystnihon.freeremote.R;
import com.mystnihon.freeremote.config.Config;
import com.mystnihon.freeremote.db.DBHelper;
import com.mystnihon.freeremote.db.table.SeedboxTable;
import com.mystnihon.freeremote.manager.file.FileManager;
import com.mystnihon.freeremote.manager.file.NotMountedStorageException;
import com.mystnihon.freeremote.settings.SettingsFactory;
import com.mystnihon.freeremote.settings.SettingsParser;
import com.mystnihon.freeremote.settings.SettingsParser.SettingsData;

@SuppressLint("NewApi")
public class SettingsImportFragment extends Fragment implements View.OnClickListener {

    private static final int REQUEST_CODE_IMPORT = 0;
    View mImport;
    View mExport;
    FileManager mFileManager;

    
    public static SettingsImportFragment newInstance() {
        SettingsImportFragment f = new SettingsImportFragment();
        return f;

    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.fragment_settings_import, null);
        mImport = v.findViewById(R.id.fr_settings_import_btn);
        mImport.setOnClickListener(this);
        mExport = v.findViewById(R.id.fr_settings_export_btn);
        mExport.setOnClickListener(this);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        try {
            mFileManager = new FileManager(getActivity());
        } catch (NotMountedStorageException e) {
            // TODO Display a message saying that the sdcard is not mounted
            mImport.setEnabled(false);
            mExport.setEnabled(false);
        }
    }

    public void onClick(View view) {
        if (view == mExport) {
            exportSettings();
        } else if (view == mImport) {
            // importSettings();
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            Uri imgUri = Uri.fromFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
            intent.setDataAndType(imgUri, "file/xml");
            startActivityForResult(intent, REQUEST_CODE_IMPORT);
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_IMPORT) {
            if (resultCode == Activity.RESULT_OK) {
                importSettings(data.getData());
            } else {
                Toast.makeText(getActivity(), R.string.pref_impexp_import_failed, Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void importSettings(Uri uri) {
        
        File file = new File(uri.getPath());
        try {
            String text = readFile(file);
            SettingsData setData = SettingsParser.parse(text);
            if (setData != null) {
                updateSettings(setData);
                Toast.makeText(getActivity(), getString(R.string.pref_impexp_import_success, uri.getLastPathSegment()), Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e) {
            Log.e("Import", "Import failed", e);
            Toast.makeText(getActivity(), R.string.pref_impexp_import_failed, Toast.LENGTH_SHORT).show();
        } catch (SAXException e) {
            Log.e("Import", "Import failed", e);
            Toast.makeText(getActivity(), R.string.pref_impexp_import_failed, Toast.LENGTH_SHORT).show();
        } catch (ParserConfigurationException e) {
            Log.e("Import", "Import failed", e);
            Toast.makeText(getActivity(), R.string.pref_impexp_import_failed, Toast.LENGTH_SHORT).show();
        }
    }

    private void exportSettings() {
        File file = new File(mFileManager.getExternalStorageDirectory(), Config.SETTINGS_FILE_NAME);
        String data = SettingsFactory.createXML(getActivity());

        try {
            writeFile(file, data);
            Toast.makeText(getActivity(), getString(R.string.pref_impexp_export_success, file.getAbsolutePath()), Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), R.string.pref_impexp_export_failed, Toast.LENGTH_LONG).show();
        }
    }

    private String readFile(File file) throws IOException {
        InputStreamReader isr = new InputStreamReader(new FileInputStream(file), Charset.defaultCharset());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line = null;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    }

    private void writeFile(File file, String text) throws IOException {
        OutputStreamWriter outWriter = new OutputStreamWriter(new FileOutputStream(file), Charset.defaultCharset());
        outWriter.write(text);
        outWriter.flush();
        outWriter.close();
    }

    private void updateSettings(SettingsData settingsData) {
        for (SeedboxTable seedbox : settingsData.seedboxList) {
            DBHelper.insertSeedbox(getActivity().getContentResolver(), seedbox);
        }
        Editor editor = PreferenceManager.getDefaultSharedPreferences(getActivity()).edit();
        editor.putBoolean(getString(R.string.pref_key_auto_start), settingsData.autoStart);
        editor.putString(getString(R.string.pref_key_remote_code), settingsData.remotecode);
        editor.putInt(getString(R.string.pref_key_seedbox_refresh_time), settingsData.refreshTime);
        editor.commit();
    }
}
